package com.app.mymusic.utils;

import android.os.Handler;
import android.os.Message;

import com.app.mymusic.model.Mp3Info;
import com.app.mymusic.model.NetMusic;
import com.app.mymusic.retrofit.DowLoadInter;
import com.app.mymusic.retrofit.ProgressListener;
import com.app.mymusic.retrofit.ProgressResponseBody;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/7/29.
 */
public class DownLoadUtil {
    private  String url;
   public void get()
   {
       HttpURLConnection conn=null;
       try {
           conn.getInputStream();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

    public static void sendMsg(Handler handler,String obj,int flag)
    {
        Message msg=handler.obtainMessage();
        msg.what=flag;
        msg.obj=obj;
        handler.sendMessage(msg);
    }



    /**
     * @param
     *            :请求接口
     * @param httpArg
     *            :参数
     * @return 返回结果
     */
    public static void  request(String httpUrl, String httpArg, Handler mHandler) {
        BufferedReader reader = null;
        String result = "";
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey",  "13e982978120a8e0218bd279e0632036");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;

            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            result = sbf.toString().trim();
            Message msg= mHandler.obtainMessage();
            msg.what=110;
            msg.obj=result;
            mHandler.sendMessage(msg);
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static void getMusic()
    {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://apis.baidu.com/geekery/music/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        InterGet interGet=retrofit.create(InterGet.class);
        String s="十年";
        interGet.query(s,"10","1")
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<NetMusic>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                LogUtil.showLog(e.toString());
            }

            @Override
            public void onNext(NetMusic n) {
               NetMusic.MusicInfo m= n.getData().getData().get(0);
                LogUtil.showLog(m.getSongname());

                LogUtil.showLog(m.getHash());
                LogUtil.showLog(n.getCode()+"**");

            }
        });


    }
    public interface InterGet
    {
        @Headers("apikey:13e982978120a8e0218bd279e0632036")
        @GET("query")
        Observable<NetMusic> query(@Query("s") String s, @Query("size") String size, @Query("page") String page);

    }

    public static void downLoadMusic(String path, final String filename, final Mp3Info m)
    {
        Retrofit.Builder retrofit=new Retrofit.Builder()
                .baseUrl("http://song.music.response.itmf.cn/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
        OkHttpClient client=new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        okhttp3.Response orginalResponse = chain.proceed(chain.request());
                        return orginalResponse.newBuilder()
                                .body(new ProgressResponseBody(orginalResponse.body(), new ProgressListener() {
                                    @Override
                                    public void onProgress(long progress, long total, boolean done) {
                                        m.setSize(total);
                                        m.setDownsize(progress);
                                        m.setDone(done);
                                        EventBus.getDefault().post(m);
                                    }
                                }))
                                .build();
                    }
                }).build();
        DowLoadInter inter=retrofit.client(client).build().create(DowLoadInter.class);
        inter.download(path)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseBody>(){
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {
                        LogUtil.showLog(e.toString());
                    }
                    @Override
                    public void onNext(ResponseBody responseBody) {
                            InputStream is = responseBody.byteStream();
                            FileUtil.write2SDCard(is,filename);
                    }
                });
    }
}


